package com.guoxin.designpattern.chapter3;

/**
 * @author guoxin
 * @date 2019/9/3
 */
public class VolatileTest {
    private static volatile int initValue = 0;
    private static final int MAX_LIMIT = 5;

    public static void main(String[] args) {
        new Thread(() -> {
            int localValue = initValue;
            while (localValue < MAX_LIMIT) {
                if (localValue != initValue) {
                    System.out.printf("The value updated to [%d]\n", initValue);
                    localValue = initValue;
                }
            }
        }, "READ").start();

        new Thread(() -> {
            int localValue = initValue;
            while (initValue < MAX_LIMIT) {
                try {
                    System.out.printf("Update the value to [%d]\n", ++localValue);
                    initValue = localValue;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "WRITE").start();
    }
}
